﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/**
 * 创建时间：2014/7/15 11:57:24
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace CUWo.Common.WebHelper
{
    public class WebTaskHelper
    {
        // 网络请求
        private readonly HttpGetRequestHelper _dataRequest;
        public WebTaskHelper(Uri url)
            : this(new HttpGetRequestHelper(url))
        {
        }
        // 创建一个网络任务
        public WebTaskHelper(HttpGetRequestHelper httpPostRequest)
        {
            this._dataRequest = httpPostRequest;
        }
        // 开始网络任务
        public IAsyncResult BeginWebTask(AsyncCallback asyncCallback, object state)
        {
            AsyncResult<string> asyncResult = new AsyncResult<string>(asyncCallback, state);
            this._dataRequest.BeginRequest(delegate(IAsyncResult o)
            {
                try
                {
                    // 获取网络返回字符串
                    string result = WebResponseToString(_dataRequest.EndRequest(o));
                    asyncResult.SetAsCompleted(result, o.CompletedSynchronously);
                }
                catch (Exception exception)
                {
                    //asyncResult.SetAsCompleted(exception, o.CompletedSynchronously);
                    asyncResult.SetAsCompleted("exception:" + exception.Message, o.CompletedSynchronously);
                }
            }, null);
            return asyncResult;
        }
        // 结束异步请求
        public string EndWebTask(IAsyncResult asyncResult)
        {
            return ((AsyncResult<string>)asyncResult).EndInvoke();
        }

        /// <summary>
        /// 处理网络请求的回应
        /// </summary>
        /// <param name="webResponse">网络回应</param>
        /// <returns>返回的字符串</returns>
        private string WebResponseToString(Stream response)
        {
            using (StreamReader reader = new StreamReader(response))
            {
                return reader.ReadToEnd();
            }
        }
    }
}
